<!--
  * 云喇叭表单
-->
<template>
  <a-modal
    :title="formData.id ? '修改台卡' : '新增台卡'"
    :width="1000"
    :open="visibleFlag"
    @cancel="onClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" :disabled="props.formType == 'view'" v-if="props.formType != 'view'">
      <a-row :gutter="16">
        <a-col :span="24">
          <group-title :iconOptions="{ class: 'text-blue-400' }">基础信息</group-title>
        </a-col>
        <a-col :span="12">
          <a-form-item label="前缀" name="codePrefix">
            <a-input v-model:value="formData.codePrefix" placeholder="请输入前缀" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="总长度" name="length">
            <a-input-number style="width: 100%" v-model:value="formData.length" :min="0" :precision="0" placeholder="请输入总长度，范围1-24" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="起始号码" name="codeNumBegin">
            <a-input-number style="width: 100%" v-model:value="formData.codeNumBegin" :min="0" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="截至号码" name="codeNumEnd">
            <a-input-number style="width: 100%" v-model:value="formData.codeNumEnd" :min="0" placeholder="请输入" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-row :gutter="16" v-if="props.formType == 'view'" class="m-t-4">
      <a-col :span="24">
        <group-title :iconOptions="{ class: 'text-blue-400' }">台卡信息</group-title>
      </a-col>
      <a-col :span="24"> 台卡设备号:{{ props.rowData.code }}</a-col>
      <a-col :span="24" v-if="!isEmpty(props.rowData.merchantId)">
        <div style="text-align: center" class="m-t-10">
          <canvas id="qrCanvas01" width="300" height="330"></canvas>
        </div>
      </a-col>
    </a-row>
    <a-row :gutter="16" v-if="props.formType == 'view'" class="m-t-4">
      <a-col :span="24">
        <group-title :iconOptions="{ class: 'text-blue-400' }">当前绑定信息</group-title>
      </a-col>
      <a-col :span="24"> 商户名称:{{ props.rowData.merchantName }}</a-col>
      <a-col :span="24"> 门店名称:{{ props.rowData.storeName }} </a-col>
    </a-row>
    <a-row :gutter="16" v-if="props.formType == 'view'" class="m-t-4">
      <a-col :span="24">
        <group-title :iconOptions="{ class: 'text-blue-400' }">绑定记录</group-title>
      </a-col>
      <a-col :span="24">
        <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false" />
      </a-col>
    </a-row>
    <template #footer>
      <a-space v-if="props.formType != 'view'">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { smartSentry } from '/@/lib/smart-sentry'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { strToArr, selectDictLabel } from '/@/utils/common'
  import { codeApi } from '/@/api/business/b-operation/code/code-api'
  import { codeLogApi } from '/@/api/business/b-operation/code/code-log-api'
  import { DEVICE_TYPE, DEVICE_STATUS } from '/@/constants/dict'
  import { commonRules } from '/@/utils/validate'
  import { useRoute } from 'vue-router'
  import { isEmpty } from 'lodash'
  const route = useRoute()
  // ---------------------------- 表格列 ----------------------------
  const cloudDevice = computed(() => {
    // 0云喇叭 1云打印
    return route.path.includes('cloud-speaker') ? 0 : 1
  })

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  const columns = ref([
    {
      title: '时间',
      dataIndex: 'cTime',
      ellipsis: true,
    },
    {
      title: '绑定对象',
      dataIndex: 'merchantName',
      customRender: (column) => {
        return `${column.text}(${column.record.no})`
      },
      ellipsis: true,
    },
  ])
  const tableData = ref([])
  const tableLoading = ref(false)

  const getDeviceLogList = async () => {
    tableLoading.value = true
    let queryParams = {
      pageSize: 100,
      pageNo: 1,
      codeId: props.rowData.id,
      sortFields: [
        {
          field: 'c_time',
          order: 'desc',
        },
      ],
    }
    try {
      let queryResult = await codeLogApi.page(queryParams)
      tableData.value = queryResult.data
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  function onReset() {
    Object.assign(formData.value, formDefault)
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    Object.assign(formData.value, formDefault)
    visibleFlag.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 获取表单数据 ------------------------
  async function getFormData(data) {
    SmartLoading.show()
    try {
      let res = await codeApi.findId(data)
      formData.value = { ...res.data }
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    codeNumBegin: undefined, //起始号码，最小值为0>= 0
    codeType: 1, //
    codePrefix: undefined, //码牌前缀，最多不超过23
    length: undefined, //总长度，范围1-24>= 1 <= 24
    codeNumEnd: undefined, //截至号码，最小值为1 >= 1
    batchId: undefined, //码牌批次，最多不超过13
    defaultPwd: undefined, //默认密码，最多不超过32
  }

  let formData = ref({ ...formDefault })

  const rules = {
    codePrefix: [{ required: true, message: '码牌前缀 必填' }],
    length: [
      { required: true, message: '总长度 必填' },
      {
        message: () => `总长度 0 到 24 之间`,
        ruleFun: (val) => {
          return val >= 0 && val <= 24
        },
        validator: commonRules,
        trigger: 'blur',
      },
    ],
    codeNumBegin: [{ required: true, message: '起始号码 必填' }],
    codeNumEnd: [{ required: true, message: '截至号码 必填' }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      let data = { ...formData.value, deviceType: cloudDevice.value }
      if (formData.value.id) {
        await codeApi.update(data)
      } else {
        await codeApi.insert(data)
      }
      message.success('操作成功')
      emits('ok')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  // ---------------------------- 二维码码牌预览 ----------------------------
  const openImg = ref(false)
  const imgUrl = ref('')
  const storeName = ref('')
  const viewMpImg = async (record) => {
    // console.log('record==>', record)
    storeName.value = record.storeName
    if (isEmpty(record.merchantId)) return
    const params = {
      merchantId: record.merchantId,
      storeId: record.id,
    }
    await codeApi.downloadActive(params).then((res) => {
      imgUrl.value = res.data.urlBase64Image
      openImg.value = true
      console.log('imgUrl1==>', imgUrl.value)
      // 使用 nextTick 确保 DOM 更新完成后再调用 makeCanvas
      nextTick(() => {
        makeCanvas()
      })
    })
  }
  const makeCanvas = () => {
    // 直接执行 canvas 操作，不等待 DOMContentLoaded 事件
    const canvas = document.getElementById('qrCanvas01')
    const ctx = canvas.getContext('2d')

    // 绘制红色背景
    ctx.fillStyle = '#B81614'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    // 二维码相关配置和绘制
    const qrSize = 200 // Size of the QR code within the canvas
    const qrMargin = 50
    const qrImage = new Image()
    qrImage.src = imgUrl.value //qrCode.createDataURL(4) // Scale factor for QR code image

    qrImage.onload = function () {
      // 绘制白色方块和二维码
      ctx.fillStyle = 'white'
      ctx.fillRect(qrMargin, qrMargin, qrSize, qrSize) // White square to contain QR code
      ctx.drawImage(qrImage, qrMargin, qrMargin, qrSize, qrSize)

      // 绘制四个角的装饰线条
      drawCornerLs(ctx, 40, 40, qrSize + 20, qrSize + 20, 20)

      // 添加门店文本信息
      ctx.fillStyle = '#fff'
      ctx.font = 'bold 16px Arial'
      ctx.textAlign = 'center'
      // ctx.fillText(storeName.value ? `门店:${storeName.value}` : '', canvas.width / 2, canvas.height - 30)
      ctx.fillText(`NO:${props.rowData.code}`, canvas.width / 2, canvas.height - 30)
    }

    /**
     * 绘制四个角的L形（开口朝中间）
     * @param {CanvasRenderingContext2D} ctx - Canvas绘图上下文
     * @param {number} x - 容器左上角x坐标
     * @param {number} y - 容器左上角y坐标
     * @param {number} width - 容器宽度
     * @param {number} height - 容器高度
     * @param {number} length - L形每条边的长度（向中间延伸的距离）
     * @param {string} [color='#fff'] - 线段颜色（默认白色）
     * @param {number} [lineWidth=3] - 线段宽度（默认3像素）
     */
    function drawCornerLs(ctx, x, y, width, height, length, color = '#fff', lineWidth = 3) {
      // 配置绘图样式（线帽设为'square'让L形角更整齐）
      ctx.strokeStyle = color
      ctx.lineWidth = lineWidth
      ctx.lineCap = 'square'

      // ---- 1. 左上角L形（上边+左边，开口向右下）----
      ctx.beginPath()
      ctx.moveTo(x, y) // 起点：左上角顶点
      ctx.lineTo(x + length, y) // 上边：向右延伸length
      ctx.moveTo(x, y) // 回到起点
      ctx.lineTo(x, y + length) // 左边：向下延伸length
      ctx.stroke()

      // ---- 2. 右上角L形（上边+右边，开口向左下）----
      ctx.beginPath()
      ctx.moveTo(x + width, y) // 起点：右上角顶点
      ctx.lineTo(x + width - length, y) // 上边：向左延伸length
      ctx.moveTo(x + width, y) // 回到起点
      ctx.lineTo(x + width, y + length) // 右边：向下延伸length
      ctx.stroke()

      // ---- 3. 右下角L形（右边+下边，开口向左上）----
      ctx.beginPath()
      ctx.moveTo(x + width, y + height) // 起点：右下角顶点
      ctx.lineTo(x + width, y + height - length) // 右边：向上延伸length
      ctx.moveTo(x + width, y + height) // 回到起点
      ctx.lineTo(x + width - length, y + height) // 下边：向左延伸length
      ctx.stroke()

      // ---- 4. 左下角L形（下边+左边，开口向右上）----
      ctx.beginPath()
      ctx.moveTo(x, y + height) // 起点：左下角顶点
      ctx.lineTo(x + length, y + height) // 下边：向右延伸length
      ctx.moveTo(x, y + height) // 回到起点
      ctx.lineTo(x, y + height - length) // 左边：向上延伸length
      ctx.stroke()
    }
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      console.log('formData.value==>', formData.value)

      if (props.open && props.rowData && props.formType != 'add') {
        // getFormData(val[0])
      }
      if (props.open && props.rowData && props.formType == 'view') {
        viewMpImg(val[0])
        getDeviceLogList()
      }
    },
    { immediate: true },
  )
</script>
